package com.jf.filter;

import com.alibaba.fastjson.JSON;
import com.jf.bean.Userinfo;
import com.jf.service.TokenService;
import com.jf.service.UserinfoService;
import com.jf.service.impl.TokenServiceImpl;
import com.jf.service.impl.UserinfoServiceImpl;
import com.jf.util.MyConstants;
import com.jf.util.MyUtils;
import com.jf.util.ResultJson;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;
import java.util.ResourceBundle;

@WebFilter("/*")
public class LoginFilter implements Filter {
    private TokenService tokenService;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        tokenService = new TokenServiceImpl();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        /*转换request和response*/
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        /*获取请求地址*/
        String url = request.getServletPath();

        /*获取配置文件*/
        ResourceBundle rb = ResourceBundle.getBundle("config");
        String[] whiteSheet = rb.getString("filter.white.sheet").split(",");
        boolean isWhite = false;
        for(String ws : whiteSheet){
            if(ws.equals(url)){
                isWhite = true;
                break;
            }
        }
        if(isWhite){
            filterChain.doFilter(request,response);
        }else{
            String token = request.getHeader("token");
            if(MyUtils.isStringEmpty(token)){
                response.getWriter().println(JSON.toJSON(ResultJson.error(401,"未携带token")));
            }else{
                if(tokenService.isLogin(token)){
                    filterChain.doFilter(request,response);
                }else{
                    response.getWriter().println(JSON.toJSON(ResultJson.error(401,"登录失效！")));
                }
            }
        }
    }

    @Override
    public void destroy() {

    }
}
